package com.fu.mr.bluetoothdchat.thread;

import android.bluetooth.BluetoothSocket;
import android.os.Handler;
import android.util.Log;

import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;

/**
 * <pre>
 *     author : Mr.Fu
 *     e-mail : 18622268981@163.com
 *     time   : 2020/03/10
 *     desc   : 蓝牙通讯线程,双方蓝牙连接后一直运行的线程.
 *              在 run() 方法中使用阻塞方式的 InputStream,read()循环读取输入流
 *              然后 post 到 UI 线程中更新消息
 *              最后 cancel() 关闭连接的 socket
 *     version: 1.0
 * </pre>
 */

public class CommunicateThread extends Thread {

    private static final String TAG = CommunicateThread.class.getSimpleName();

    private BluetoothSocket mSocket;
    private Handler mHandler;
    private final InputStream mInStream;

    private CommunicateListener mListener;

    public CommunicateThread(BluetoothSocket socket, Handler handler) {

        mSocket = socket;
        mHandler = handler;

        InputStream tmpIn = null;
        OutputStream tmpOut = null;
        try {
            tmpIn = socket.getInputStream();
            tmpOut = socket.getOutputStream();
        } catch (IOException e) {
            Log.e(TAG, "temp sockets not created", e);
        }

        mInStream = tmpIn;
    }

    @Override
    public void run() {

        Log.d(TAG, "CommunicateThread -> run");
        byte[] buffer = new byte[1024];
        int bytes;
        while (true) {
            try {
                try {
                    //  当有数据流入时，线程休眠一段时间，默认1000ms,
                    //  由 100 扩大到 1000, 防止数据较大时,数据丢失
                    Thread.sleep(1000);
                } catch (InterruptedException e) {
                    e.printStackTrace();
                }
                bytes = mInStream.read(buffer);
                mHandler.obtainMessage(0, bytes, -1, buffer).sendToTarget();
            } catch (IOException e) {
                e.printStackTrace();
                if (mListener != null) {
                    mListener.onConnectionLost();
                }
                break;
            }
        }
    }

    public void cancel() {

        Log.w(TAG, "CommunicateThread -> cancel()");
        if (mSocket != null) {
            try {
                mSocket.close();
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
    }

    public void setCommunicateListener(CommunicateListener listener) {

        mListener = listener;
    }

    public static interface CommunicateListener {

        void onConnectionLost();
    }
}
